<?php

namespace App\Http\Controllers\Api;

use App\Jobs\SendWechatTemplate;
use App\Models\Area;
use App\Models\BackOrder;
use App\Models\Banner;
use App\Models\Book;
use App\Models\SellCart;
use App\Models\SellOrder;
use App\Models\SellOrderExpressInfo;
use App\Models\SysConfig;
use App\Models\User;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use EasyWeChat;

class SellOrderController extends BaseController
{
    public function times()
    {
        $result = [];

        $array = ["周日","周一","周二","周三","周四","周五","周六"];

        for ($i = 1; $i <= 5; $i++)
        {
            $day_timestamp = strtotime("+{$i} days");
            if($i == 1)
            {
                $day = '明天('.date('m月d日',$day_timestamp).')';
            }
            else
            {
                $day = $array[date("w",$day_timestamp)].'('.date('m月d日',$day_timestamp).')';
            }

            $times = [];
            for ($j = 1; $j <= 9; $j++)
            {
                if($i == 1)
                {
                    $start_time = strtotime(date('Y-m-d').' 15:00:00');
                    $end_time = strtotime(date('Y-m-d').' 23:59:59');
                    //就是当天15:00-24:00之间时间的订单，选择明天的时间，只能选15:00-18:00之间的3个时间段，其他都是正常
                    if($this->time >= $start_time && $this->time <= $end_time)
                    {
                        if(in_array($j,[1,2,3,4,5,6]))
                        {
                            continue;
                        }
                    }
                }
                switch ($j)
                {
                    case 1:
                        $title = '9:00-10:00';
                        $value = date('Y-m-d',$day_timestamp).' 09:00:00';
                        break;
                    case 2:
                        $title = '10:00-11:00';
                        $value = date('Y-m-d',$day_timestamp).' 10:00:00';
                        break;
                    case 3:
                        $title = '11:00-12:00';
                        $value = date('Y-m-d',$day_timestamp).' 11:00:00';
                        break;
                    case 4:
                        $title = '12:00-13:00';
                        $value = date('Y-m-d',$day_timestamp).' 12:00:00';
                        break;
                    case 5:
                        $title = '13:00-14:00';
                        $value = date('Y-m-d',$day_timestamp).' 13:00:00';
                        break;
                    case 6:
                        $title = '14:00-15:00';
                        $value = date('Y-m-d',$day_timestamp).' 14:00:00';
                        break;
                    case 7:
                        $title = '15:00-16:00';
                        $value = date('Y-m-d',$day_timestamp).' 15:00:00';
                        break;
                    case 8:
                        $title = '16:00-17:00';
                        $value = date('Y-m-d',$day_timestamp).' 16:00:00';
                        break;
                    case 9:
                        $title = '17:00-18:00';
                        $value = date('Y-m-d',$day_timestamp).' 17:00:00';
                        break;

                }

                $times[] = [
                    'title' => $title,
                    'value' => $value
                ];
            }



            $result[] = [
                'day' => $day,
                'times' => $times
            ];
        }

        return $this->ok($result);
    }

    public function submit(Request $request)
    {
        $ids = trim($request->get('ids'));
        $address_id = intval($request->get('address_id'));

        if(empty($ids))
        {
            return $this->err(1,200,'','参数错误');
        }

        $sysConfigModel = new SysConfig();
        $config = $sysConfigModel->getSellCartConfig();

        $books = [];
        $total_price = 0;  //预估总价

        $ids_arr = explode(',',$ids);
        if(!empty($ids_arr))
        {
            foreach ($ids_arr as $v)
            {
                $row = SellCart::query()->where('id',$v)->first();
                $books[] = [
                    'book_id'       => $row->book_id,
                    'book_title'    => $row->book_title,
                    'book_image'    => $row->book_image,
                    'recyle_price'  => $row->recyle_price,
                ];
                $total_price += $row->recyle_price;
            }
        }

        $total_price = round($total_price,1);
        if(count($books) < $config['config_book_num'] &&  $total_price < $config['config_total_price'])
        {
            return $this->err(1,200,'','提交失败');
        }

        if(count($books) > 99)
        {
            return $this->err(1,200,'','下单失败，每次最多只能卖99本');
        }

        if(!empty($address_id))
        {
            $address = UserAddress::query()->where('id',$address_id)->where('user_id',$this->user_id)->where('deleted',0)->first();
        }
        else
        {
            $address = UserAddress::query()->where('deleted',0)->where('user_id',$this->user_id)->where('is_default',1)->first();
        }


        $result = [
            'address'       => $address ? $address : (object)null,
            'books'         => $books,
            'fee_price'     => 0.0,
            'total_price'   => $total_price,
        ];
        return $this->ok($result);
    }


    public function store(Request $request)
    {
        $address_id     = intval($request->get('address_id'));
        $items          = trim($request->get('items'));//[{"book_id":10},{"book_id":10}]
        $express_time   = trim($request->get('express_time'));

        //检测是否在黑名单中
        $user = User::query()->where('id',$this->user_id)->first();
        if($user->is_black == 1)
        {
            return $this->err(1021,200,'','因检测到您多次恶意将盗版或品相不合格的书卖给我们，您账号的卖书权限被暂停使用，如有疑问请咨询客服');
        }

        if(empty($address_id))
        {
            return $this->err(1,200,'','快递上门取件地址不能为空');
        }

        if(empty($items))
        {
            return $this->err(1,200,'','参数错误');
        }

        if(empty($express_time))
        {
            return $this->err(1,200,'','快递上门时间不能为空');
        }

        $items = json_decode($items,true);
        if(empty($items) || !is_array($items))
        {
            return $this->err(1,200,'','参数错误');
        }

        $sysConfigModel = new SysConfig();
        $config = $sysConfigModel->getSellCartConfig();

        $address = UserAddress::query()->where('id',$address_id)->first();
        if(empty($address) || $address->user_id != $this->user_id || $address->deleted)
        {
            return $this->err(1,200,'','收货地址有误');
        }

        $express_time = strtotime($express_time);
        if($express_time <= $this->time)
        {
            return $this->err(1,200,'','快递上门时间有误');
        }

        $province = Area::query()->where('id',$address->province_id)->first();
        $is_far = 0;
        if(!empty($province) && $province->is_far == 1)
        {
            //偏远地区
            $is_far = 1;
        }
        if($is_far)
        {
            return $this->err(1020,200,'','偏远地区暂时不收');
        }

        $bookModel = new Book();
        $total_price = 0;  //预估总价
        foreach ($items as $item)
        {
            //$book = $bookModel->getBookInfo($item['book_id']);
            $book = Book::query()->where('id',$item['book_id'])->first();
            if(empty($book))
            {
                return $this->err(1,200,'','图书不存在');
            }
            $book = $book->toArray();
            if($book['is_recycle'] != 1)
            {
                return $this->err(1,200,'','抱歉，平台暂时不收《'.$book['title'].'》这本书！我们会根据市场及库存情况动态调整收书范围。');
            }

            $total_price += $book['recyle_price'];
        }

        $total_price = round($total_price,1);
        if(count($items) < $config['config_book_num'] &&  $total_price < $config['config_total_price'])
        {
            return $this->err(1,200,'','提交失败');
        }

        $user = User::query()->select(['id','wechat_openid','unionid','wechat_nickname'])->where('id',$this->user_id)->first();

        \DB::beginTransaction();    //主事务
        try {
            $order = new SellOrder([
                'total_price'                   => $total_price,
                'deliver_address_id'            => $address_id,
                'deliver_name'                  => $address->receiver,
                'deliver_mobile'                => $address->mobile,
                'deliver_address_province'      => $address->province_name,
                'deliver_address_city'          => $address->city_name,
                'deliver_address_area'          => $address->area_name,
                'deliver_address_detail'        => $address->address,
                'created_at'                    => $this->time,
                'updated_at'                    => $this->time,
                'state'                         => 1,
                'user_openid'                   => $user->wechat_openid,
                'user_nickname'                 => $user->wechat_nickname,
                'express_time'                  => $express_time,
            ]);
            // 订单关联到当前用户
            $order->user()->associate($user);
            // 写入数据库
            $order->save();

            foreach ($items as $item)
            {
                $book = Book::find($item['book_id']);
                $item = $order->sell_order_items()->make([
                    'book_id'           => $item['book_id'],
                    'book_title'        => $book['title'],
                    'book_image'        => $book['image'],
                    'book_author'       => $book['author'],
                    'review'            => '',
                    'book_recyle_price' => $book['recyle_price'],
                    'user_id'           => $this->user_id,
                ]);
                $item->save();
            }

            $userAddressModel = new UserAddress();
            $userAddressModel->setDefaultAddress($address_id,$this->user_id);

            // 将从购物车中移除
            $bookIds = collect($items)->pluck('book_id');
            $user->sell_carts()->whereIn('book_id', $bookIds)->delete();

            $user->increment('sell_orders_num');
            \DB::commit();

            /*$officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $first = "卖书订单已提交成功，等待审核\r\n";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                    'url'  => '',
                    'data' => [
                        'first'         => $first,
                        'OrderSn'       => $order->no,
                        'OrderStatus'   => '订单提交成功'."\r\n",
                        'remark'        => '我们会尽快对订单进行审核，审核通过后将为您安排快递上门取书，请留意通知。'
                    ],
                ]);
            }*/

            //使用异步队列
            $job_params = [
                'user_id'       => $order->user_id,
                'template_id'   => 'fDri6AUO73KHgibmDn8v8vm1esCaNMCML_eesYlb6Ns',
                'sell_order_id' => $order->id,
                'type'          => 1,
            ];
            dispatch(new SendWechatTemplate($job_params));

            $banner = Banner::query()->where('position',4)->where('is_show',1)->first();

            $banner_item = [];
            if(!empty($banner))
            {
                $banner_item = [
                    'image' => $banner->image,
                    'url'   => $banner->url,
                ];
            }

            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $officialAccount->template_message->send([
                'touser'        => 'oKOD01EmbGyVy9nEgrq7N6Hh-BG0',
                'template_id'   => 'T2LwyJ_zHil6B0QfKDKfjUL19358TPQlVVoJ6reMMrU',
                'url'  => '',
                'miniprogram' => [
                    'appid'     => config('wechat.mini_program.default.app_id'),
                    'path'  => '',
                ],
                'data' => [
                    'first'     => '后台有新的回收订单,请尽快审核'."\r\n",
                    'keyword1'  => $order->no,
                    'keyword2'  => '快鱼二手书',
                    'keyword3'  => date('Y-m-d H:i:s',$this->time)."\r\n",
                    'remark'    => ''
                ],
            ]);

            /*$sms = app('easysms');
            try {
                $sms->send('15888825922',[
                    'template' => 'SMS_167963981',
                    'data' => [

                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                //dd($message);
            }*/

            return $this->res([
                'data' => [
                    'order_id'  => $order->id,
                    'order_no'  => $order->no,
                    'banner'    => $banner_item,
                ]
            ]);
        } catch (\Exception $e) {
            \DB::rollBack();
            //echo $e->getMessage();
            return $this->err(1,200,$e->getMessage(),'下单失败');
        }
    }

    public function express(Request $request)
    {
        $sell_order_id = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = SellOrder::query()->where('id',$sell_order_id)->first();
        if(empty($order) || $order->user_id != $this->user_id)
        {
            //return $this->err(1,200,'','订单不存在');
        }

        $row = SellOrderExpressInfo::query()->where('sell_order_id',$sell_order_id)->orderBy('id','desc')->first();
        $result = [];

        if(!empty($row))
        {
            $result = [
                'sell_order_id' => $row->sell_order_id,
                'address'       => $order->deliver_address_province.$order->deliver_address_city.$order->deliver_address_area.$order->deliver_address_detail,
                'name'          => $order->deliver_name,
                'mobile'        => $order->deliver_mobile,
                'express_no'    => $row->express_no,
                'state'         => $row->state,
                'trces'         => $row->traces ? array_reverse(json_decode($row->traces,true)) : [],
            ];
        }
        return $this->ok($result);
    }

    public function show(Request $request)
    {
        $sell_order_id = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }
        $order = SellOrder::query()->with(['sell_order_items'])->where('id',$sell_order_id)->first();
        if(empty($order) || $order->user_id != $this->user_id)
        {
            return $this->err(1,200,'','订单不存在');
        }


        $back_order = BackOrder::query()->where('user_id',$this->user_id)->where('sell_order_id',$sell_order_id)->where('state','>',0)->first();

        $books = [];
        $back_book_num = 0;
        $medium_num = 0;
        $medium_price = 0;
        $unpass_price = 0;
        $unpass_num = 0;

        if(!empty($order->sell_order_items))
        {
            foreach ($order->sell_order_items as $v)
            {
                if($v->first_check_state == 1)
                {
                    if($v->state == 2)
                    {
                        $unpass_price += $v->book_recyle_price;
                        $back_book_num++;
                        $unpass_num ++;
                    }
                    elseif($v->state == 1)
                    {
                        if($v->type >= 3)
                        {
                            $medium_num++;
                            $medium_price += round($v->book_recyle_price - $v->actual_recyle_price,1);
                        }
                    }
                    elseif($v->state == 3)
                    {
                        $unpass_num ++;
                        $unpass_price += $v->book_recyle_price;
                    }
                }


                //审核通过后  包含未通过的图书
                if($v->first_check_state == 0 && $order->state > 1)
                {
                    $unpass_price += $v->book_recyle_price;
                    $unpass_num ++;
                }

                $books[] = [
                    'book_id'               => $v->book_id,
                    'book_title'            => $v->book_title,
                    'book_author'           => $v->book_author,
                    'book_image'            => $v->book_image,
                    'book_recyle_price'     => $v->book_recyle_price,
                    'first_check_state'     => $v->first_check_state,
                    'actual_recyle_price'   => $v->actual_recyle_price,
                    'state'                 => $v->state,
                    'type'                  => $v->type,
                    'reason'                => $v->reason,
                ];
            }
        }

        //计算回退运费
        $back_fee_price = 0;
        /*if($back_book_num)
        {
            if($back_book_num <= 4)
            {
                $back_fee_price = 7;
            }
            else
            {
                $back_fee_price = 7 + ceil(($back_book_num-4)/3)*2;
            }
        }*/


        $back_order_id = 0;
        $can_back = 1;
        if(!empty($back_order))
        {
            $back_order_id = $back_order->id;
            $can_back = 0;
        }

        if($back_book_num == 0)
        {
            $can_back = 0;
        }

        if($this->time > (72*3600+$order->platform_success_time))
        {
            //计算能否取回退回的书
            $can_back = 0;
        }


        /*$express_info = SellOrderExpressInfo::query()->where('sell_order_id',$order->id)->first();
        if(!empty($express_info))
        {
            $traces = json_decode($express_info->traces,true);
        }*/
        //var_dump($traces);die;
        $unpass_price = round($unpass_price,1);
        $medium_price = round($medium_price,1);
        $back_fee_price = round($back_fee_price,1);

        $result = [
            'id'                                => $order->id,
            'user_id'                           => $order->user_id,
            'no'                                => $order->no,
            'deliver_address_id'                => $order->deliver_address_id,
            'deliver_address_province'          => $order->deliver_address_province,
            'deliver_address_city'              => $order->deliver_address_city,
            'deliver_address_area'              => $order->deliver_address_area,
            'deliver_address_detail'            => $order->deliver_address_detail,
            'deliver_name'                      => $order->deliver_name,
            'deliver_mobile'                    => $order->deliver_mobile,
            'fee_price'                         => $order->fee_price,
            'created_at'                        => $order->created_at,
            'total_price'                       => $order->total_price,
            'actual_price'                      => $order->actual_price,
            'express_time'                      => $order->express_time,
            'state'                             => $order->state,
            'cancel_user'                       => $order->cancel_user,
            'cancel_time'                       => $order->cancel_time,
            'is_overtime'                       => $order->is_overtime,
            'express_no'                        => $order->express_no,
            'can_back'                          => $can_back,
            'platform_confirm_time'             => $order->platform_confirm_time,
            'platform_success_time'             => $order->platform_success_time,
            'back_book_num'                     => $back_book_num,
            'back_fee_price'                    => $back_fee_price,
            'back_order_id'                     => $back_order_id,
            'unpass_price'                      => $unpass_price,  //拒收书扣除的价格
            'unpass_num'                        => $unpass_num,
            'medium_price'                      => $medium_price,  //品相中等扣除的价格
            'medium_num'                        => $medium_num,  //品相中等图书数量
            'books'                             => $books,
        ];
        return $this->ok($result);
    }

    public function cancel(Request $request)
    {
        $sell_order_id = intval($request->get('sell_order_id'));
        if(empty($sell_order_id))
        {
            return $this->err(1,200,'','参数错误');
        }
        $order = SellOrder::query()->with(['sell_order_items'])->where('id',$sell_order_id)->first();
        if(empty($order) || $order->user_id != $this->user_id)
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state == 1 || $order->state == 2)
        {
            $cancel_sf_result = '';
            if($order->state == 2)
            {
                //还要取消快递上门
                $params = [
                    'ShipperCode'   => $order->shipper_code,
                    'OrderCode'     => $order->express_order_no,
                    'LogisticCode'  => $order->express_no,
                ];
                //调用在线取消订单
                $jsonParam = json_encode($params, JSON_UNESCAPED_UNICODE);
                $jsonResult = $this->_cancelOrder($jsonParam);


                //解析返回结果
                $result = json_decode($jsonResult, true);
                //print_r($result);die;
                if($result['Success'] && $result['ResultCode'] == 100)
                {

                }

                $cancel_sf_result = json_encode($result);
            }

            $order->update([
                'state'             => -2,
                'updated_at'        => $this->time,
                'is_closed'         => 1,
                'cancel_user'       => 0,
                'cancel_time'       => $this->time,
                'cancel_sf_result'  => $cancel_sf_result,
            ]);

            return $this->ok([]);
        }
        return $this->err(1,200,'','操作失败');
    }

    private function _cancelOrder($requestData)
    {
        $url = 'http://api.kdniao.com/api/eorderservice';
        $ebusinessid = '1363157';
        $appkey = 'f426aae4-89fa-4a90-863c-08c96328b7f6';
        $datas = array(
            'EBusinessID' => $ebusinessid,
            'RequestType' => '1004',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = kdniao_encrypt($requestData, $appkey);

        $result = sendPost($url, $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }
}
